<?php

namespace app\admin\controller\service\order;

use app\common\controller\Backend;
use think\Db;
use addons\service\library\Refund;
use app\api\model\service\Order AS OrderModel;
use think\Exception;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\service\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\order\Order;
        $this->view->assign("traveltypeList", $this->model->getTraveltypeList());
        $this->view->assign("chooseSkillTypeList", $this->model->getChooseSkillTypeList());
        $this->view->assign("paytypeList", $this->model->getPaytypeList());
        $this->view->assign("toShopList", $this->model->getToShopList());
        $this->view->assign("isServiceList", $this->model->getIsServiceList());
        $this->view->assign("isComplaintList", $this->model->getIsComplaintList());
        $this->view->assign("isPoolList", $this->model->getIsPoolList());
        $this->view->assign("isSettleList", $this->model->getIsSettleList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        
        foreach ($list as &$val)
        {
            $val->user = db('user')->where('id',$val->user_id)->field('avatar,nickname,mobile')->find();
            $val->address = db('service_order_address')->where('order_id',$val->id)->field('name,sex,mobile,province,city,district,area,address')->find();
            $val->detail = db('service_order_detail')->where('order_id',$val->id)->field('name,image,sku_name,num,price,sumprice')->find();
            $val->skill = $val->skill_id?db('service_skill')->field('name,mobile,image')->where('id',$val->skill_id)->find():'';
            $val->shop = $val->shop_id?db('service_shop')->where('id',$val->shop_id)->field('name,abbr,logo_image,leader_name,leader_mobile')->find():'';
            $val->skillRebate = $val->is_settle == 2?db('service_rebate')->where(['order_id'=>$val->id,'type'=>0])->sum('num'):0.00;
            $val->shopRebate = $val->is_settle == 2?db('service_rebate')->where(['order_id'=>$val->id,'type'=>1])->sum('num'):0.00;
            $val->create_time = date("Y-m-d H:i:s",$val->createtime);
        }
        $listItems = $list->items();
        $newList = [];
        
        foreach ($listItems as $item) {
            $v = $item->toArray(); // 模型对象转数组
           if(!empty($v['user']) && !empty($v['user']['avatar'])){
        if(strpos($v['user']['avatar'], 'http') === false) {
        $v['user']['avatar'] = 'https://q.xiangzhiapp.cn/'.$v['user']['avatar'];
            }
        }
        if(!empty($v['detail']) && !empty($v['detail']['image'])){
            if(strpos($v['detail']['image'], 'http') === false) {
                $v['detail']['image'] = 'https://q.xiangzhiapp.cn/'.$v['detail']['image'];
            }
        }
        if(!empty($v['skill']) && !empty($v['skill']['image'])){
            if(strpos($v['skill']['image'], 'http') === false) {
                $v['skill']['image'] = 'https://q.xiangzhiapp.cn/'.$v['skill']['image'];
            }
        }
        if(!empty($v['shop']) && !empty($v['shop']['logo_image'])){
            if(strpos($v['shop']['logo_image'], 'http') === false) {
                $v['shop']['logo_image'] = 'https://q.xiangzhiapp.cn/'.$v['shop']['logo_image'];
            }
        }
        
        if(!empty($v['reach_images'])){
            if(strpos($v['reach_images'], 'http') === false) {
            $v['reach_images'] = 'https://q.xiangzhiapp.cn/'.$v['reach_images'];
                }
        }
        if(!empty($v['finish_images'])){
            if(strpos($v['finish_images'], 'http') === false) {
            $v['finish_images'] = 'https://q.xiangzhiapp.cn/'.$v['finish_images'];
                }
        }
            
            $newList[] = $v;
        }
        
        $result = [
            'total' => $list->total(),
            'rows'  => $newList
        ];
        return json($result);
    }


    public function info($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 添加域名
        $row->reach_images = addImageDomain(
            $row->reach_images ? explode(',', $row->reach_images) : []
        );
        
        $row->finish_images = addImageDomain(
            $row->finish_images ? explode(',', $row->finish_images) : []
        );
        //地址,项目,技师,商户,附加项目,补差价
        $user = db('user')->where('id',$row->user_id)->field('avatar,nickname,mobile')->find();
        $shop = $row->shop_id?db('service_shop')->field('name,leader_mobile,province,city,district,address')->where('id',$row->shop_id)->find():'';
        $skill = $row->skill_id?db('service_skill')->field('name,mobile,image,province,city,district,address')->where('id',$row->skill_id)->find():'';
        $address = db('service_order_address')->field('name,sex,mobile,province,city,district,area,address')->where('order_id',$ids)->find();
        $detail = db('service_order_detail')->field('name,image,sku_name,num,price,sumprice')->where('order_id',$ids)->find();
        $addList = \app\api\model\service\AddOrder::getOrderDetailList($ids);
        $premiumList = db('service_premium_order')->field('paytype,orderId,payprice,paytime')->where(['order_id'=>$ids,'state'=>1])->select();
        $logList = db('service_order_log')->field('type,content,createtime')->where(['order_id'=>$ids])->order('id desc')->select();
        $skillRebate = $row->is_settle == 2?db('service_rebate')->where(['order_id'=>$row->id,'type'=>0])->sum('num'):0.00;
        $shopRebate = $row->is_settle == 2?db('service_rebate')->where(['order_id'=>$row->id,'type'=>1])->sum('num'):0.00;
        if(!empty($user['avatar'])){
            if(strpos($user['avatar'], 'http') === false) {
            $user['avatar'] = 'https://q.xiangzhiapp.cn/'.$user['avatar'];
                }
        }
        if(!empty($skill['image'])){
            if(strpos($skill['image'], 'http') === false) {
            $skill['image'] = 'https://q.xiangzhiapp.cn/'.$skill['image'];
                }
        }
        if(!empty($detail['image'])){
            if(strpos($detail['image'], 'http') === false) {
            $detail['image'] = 'https://q.xiangzhiapp.cn/'.$detail['image'];
                }
        }
        $this->view->assign([
            'user'=>$user,
            'skillRebate'=>$skillRebate,
            'shopRebate'=>$shopRebate,
            'order'=>$row,
            'to_shop'=>$row->to_shop,
            'shop'=>$shop,
            'skill'=>$skill,
            'address'=>$address,
            'detail'=>$detail,
            'addList'=>$addList,
            'premiumList'=>$premiumList,
            'logList'=>$logList
        ]);
        return $this->view->fetch();
    }


    public function updateskill($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status > 2 && $this->error('当前服务人员已出发,无法更换服务者');
        $row->to_shop == 'shop' && $this->error('到店核销订单无需更换服务者');
        if($this->request->isPost()){
            $params = input('post.');
            $skill = \app\admin\model\service\skill\Skill::where('id',$params['skill_id'])->field('id,shop_id')->find();
            $order =  \app\admin\model\service\order\Order::where('id',$params['id'])->field('id,user_id,to_shop,starttime,actendtime')->find();
            $exist = \app\api\model\service\SkillTime::where(['skill_id'=>$skill['id'],'state'=>['in',[1,2]],'starttime'=>['between',[$order['starttime'],$order['actendtime']]]])->value('id');
            $exist && $this->error('当前项目时间区间有被预约');
            $update['skill_id'] = $skill['id'];
            if($row->is_pool == 1)
            {
                $update['is_pool'] = 0;
            }
            if($skill['shop_id'])
            {
                $update['shop_id'] = $skill['shop_id'];
            }
            db('service_order')->where('id',$params['id'])->update($update);
            \app\api\model\service\SkillTime::updateSkillTime(['skill_id'=>$params['skill_id'],'starttime'=>$order['starttime'],'actendtime'=>$order['actendtime']],1);
            db('service_order_log')->insert(['order_id'=>$ids,'user_id'=>$row->user_id,'type'=>16,'content'=>'平台已分配服务者','createtime'=>time()]);
            $skillOpenid = \app\api\model\service\UserInfo::getOpenid($params['skill_id'],1);
            \app\api\model\service\Order::createOrderTemplateParams(['id'=>$params['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>1,'templateAttr'=>'skill_order_template','openid'=>$skillOpenid]);
            $this->success('分配成功');
        }
        
        // return $row;
        $map['state'] = 1;
        $map['city'] = $row->city;
        // 客户要这么改的，服务者的goods_ids字段保存的全是项目分类的二级id
        $two_category_id = \app\admin\model\service\Goods::where(['id'=>$row->goods_id])->value('two_category_id');
        $map[] = ['exp', Db::raw("FIND_IN_SET('$two_category_id',goods_ids)")];
        if($row->shop_id)
        {
            $map['shop_id'] = $row->shop_id;
        }
        $goodsId = $row->goods_id;
        $list = \app\admin\model\service\skill\Skill::where($map)->field('id,name')->select();
        $this->assign(['id'=>$ids,'skillList'=>$list,'row'=>$row]);
        return $this->view->fetch();
    }


    public function updateshop($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status > 1 && $this->error('当前服务人员已出发,无法更换商户');
        $row->to_shop == 'shop' && $this->error('到店核销订单无需更换商户');
        if($this->request->isPost()){
            $params = input('post.');
            $shopId = \app\admin\model\service\shop\Shop::where('id',$params['shop_id'])->value('id');
            $order =  \app\admin\model\service\order\Order::where('id',$params['id'])->field('id,user_id,to_shop')->find();
            db('service_order')->where('id',$params['id'])->update(['shop_id'=>$shopId,'is_pool'=>0]);
            db('service_order_log')->insert(['order_id'=>$ids,'user_id'=>$row->user_id,'type'=>14,'content'=>'平台已分配商户','createtime'=>time()]);
            $shopOpenid = \app\api\model\service\UserInfo::getOpenid($params['shop_id'],2);
            \app\api\model\service\Order::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>2,'templateAttr'=>'shop_order_template','openid'=>$shopOpenid]);
            $this->success('分配成功');
        }
        $map['state'] = 1;
        $map['city'] = $row->city;
        // 客户要这么改的，商铺和项目的关联是一级分类 category_id
        $category_id = \app\admin\model\service\Goods::where(['id'=>$row->goods_id])->value('category_id');
        $map[] = ['exp',Db::raw("FIND_IN_SET('$category_id',category_ids)")];
        $list = \app\admin\model\service\shop\Shop::where($map)->field('id,name')->select();
        $this->assign(['id'=>$ids,'shopList'=>$list]);
        return $this->view->fetch();
    }



    public function handleOrder()
    {
        $params = input('get.','');
        Db::startTrans();
        $order = \app\api\model\service\Order::where(['id'=>$params['ids']])->lock(true)->find();
        !in_array($order['status'],[1,2,3,4,5]) && $this->error('订单状态异常,无法操作');
        ($params['state'] == 2 && empty($order['skill_id'])) && $this->error('请先分配订单服务者');
        try{
            switch ($params['state'])
            {
                case 2:
                    OrderModel::accept(['id'=>$order['id'],'skill_id'=>$order['skill_id']]);
                    break;
                case 3:
                    OrderModel::go(['id'=>$order['id']]);
                    break;
                case 4:
                    OrderModel::reach(['id'=>$order['id']]);
                    break;
                case 5:
                    OrderModel::skillStart(['id'=>$order['id']]);
                    break;
                case 6:
                    OrderModel::skillFinish(['id'=>$order['id']]);
                    break;
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('订单状态更新失败',$e->getMessage());
        }
        $this->success('订单状态已更新');
    }


    public function refund($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->is_service == 2 && $this->error('请勿重复取消');
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $actTravelPrice = sprintf("%.2f",$params['act_travel_price']);
            $refundPrice = sprintf("%.2f",$params['refund_price']);
            !in_array($row->paytype,[0,4]) && $this->error('当前支付方式无法进行退款');
            $totalPrice = sprintf("%.2f",$refundPrice);
            $allPrice = bcadd($actTravelPrice,$refundPrice,2);
            $allPrice>$row->payprice && $this->error('退款总额不能超过支付总额');
            $settlePrice = bcsub(($row->payprice-$actTravelPrice),$refundPrice,2);
            if($row->paytype == 0){
                $refund = new Refund();
                $re = $refund->wxRefund(['out_trade_no'=>$row->orderId,'transaction_id'=>$row->trade_no,'order_price'=>$row->payprice,'refund_price'=>$totalPrice]);
                $re != 'SUCCESS' && $this->error('无法进行微信退款,请联系管理员');
            }else{
                \app\api\model\service\User::money(+$totalPrice,$row->user_id,'订单取消退款');
            }
            $settleDay = $row->shop_id?\app\api\model\service\Shop::getSettleDay($row->shop_id):\app\api\model\service\ProjectConfig::getProjectConfig('settle_day');
            $settletime = $settleDay*86400+time();
            $update = ['is_service'=>2,'finishtime'=>time(),'is_settle'=>1,'act_travel_price'=>$actTravelPrice,'refund_price'=>$refundPrice,'settle_price'=>$settlePrice,'settletime'=>$settletime];
            if($row->skill_id)
            {
                $update['skill_percent'] = \app\admin\model\service\skill\Skill::where('id',$row->skill_id)->value('percent');
            }
            if($row->shop_id)
            {
                $update['shop_percent'] = \app\admin\model\service\shop\Shop::where('id',$row->shop_id)->value('percent');
            }
            $this->model->where('id',$params['id'])->update($update);
            db('service_order_log')->insert(['order_id'=>$ids,'user_id'=>$row->user_id,'type'=>9,'content'=>'平台已取消订单','createtime'=>time()]);
            $refundExist = \app\admin\model\service\order\Refundorder::where('order_id',$params['id'])->value('id');
            if($refundExist)
            {
                \app\admin\model\service\order\Refundorder::where('order_id',$params['id'])->update(['state'=>1]);
            }
            $userOpenid = \app\api\model\service\UserInfo::getOpenid($row->user_id,0);
            OrderModel::createRefundTemplateParams(['id'=>$row->id,'state'=>1,'type'=>0,'templateAttr'=>'user_sales_template','openid'=>$userOpenid,'note'=>'已退款']);
            $this->success('已退款');
        }
        $detail = db('service_order_detail')->field('name,image,sku_name,num,price,sumprice')->where('order_id',$ids)->find();
        $addList = db('service_add_order_detail')->field('name,cost_seconds,num,price')->where(['order_id'=>$ids])->select();
        $this->assign(['id'=>$ids,'row'=>$row,'detail'=>$detail,'addList'=>$addList]);
        return $this->view->fetch();
    }


}
